<template>
  <div class="app-container">

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="Plus" @click="handleAdd" v-hasPermi="['cm:cmCategory:add']">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="info" plain icon="Sort" @click="toggleExpandAll">展开/折叠</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-if="refreshTable" v-loading="loading" :data="cmCategoryList" row-key="id" :default-expand-all="isExpandAll" :tree-props="{children: 'children', hasChildren: 'hasChildren'}">
      <el-table-column label="栏目名称" align="center" prop="categoryTitle" />
      <el-table-column label="缩略图" align="center" prop="categoryImg" width="100">
        <template #default="scope">
          <image-preview :src="scope.row.categoryImg" :width="50" :height="50"/>
        </template>
      </el-table-column>
<!--      <el-table-column label="关键字" align="center" prop="categoryKeyword" />-->
      <el-table-column label="栏目类型" align="center" prop="categoryType">
        <template #default="scope">
          <dict-tag :options="cm_category_type" :value="scope.row.categoryType"/>
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" />
      <el-table-column label="仅管理员" align="center" prop="isAdmin">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.isAdmin"/>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['cm:cmCategory:edit']">修改</el-button>
          <el-button link icon="Plus" @click="handleAdd(scope.row)" v-hasPermi="['cm:cmCategory:add']">新增</el-button>
          <el-button link icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['cm:cmCategory:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 添加或修改栏目管理对话框 -->
    <el-dialog :title="title" v-model="open" width="500px" append-to-body>
      <el-form ref="cmCategoryRef" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="上级栏目" prop="parentId">
          <el-tree-select v-model="form.parentId" :data="cmCategoryOptions" :props="{ value: 'id', label: 'categoryTitle', children: 'children' }" value-key="id" placeholder="请选择" check-strictly default-expand-all/>
        </el-form-item>
        <el-form-item label="栏目名称" prop="categoryTitle">
          <el-input v-model="form.categoryTitle" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="缩略图" prop="categoryImg">
          <image-upload v-model="form.categoryImg"/>
        </el-form-item>
        <el-form-item label="关键字" prop="categoryKeyword">
          <el-input v-model="form.categoryKeyword" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="栏目类型" prop="categoryType">
	        <el-radio-group v-model="form.categoryType">
		        <el-radio v-for="dict in cm_category_type" :key="dict.value"  :label="parseInt(dict.value)">{{dict.label}}</el-radio>
	        </el-radio-group>
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="form.sort" placeholder="请输入" />
        </el-form-item>
        <el-form-item label="仅管理员" prop="isAdmin">
          <el-radio-group v-model="form.isAdmin">
            <el-radio v-for="dict in sys_yes_no" :key="dict.value"  :label="parseInt(dict.value)">{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="CmCategory">
import { listCmCategory, getCmCategory, delCmCategory, addCmCategory, updateCmCategory } from "@/api/cm/cmCategory";

const { proxy } = getCurrentInstance();
const { cm_category_type, sys_yes_no } = proxy.useDict('cm_category_type', 'sys_yes_no');

const cmCategoryList = ref([]);
const cmCategoryOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const title = ref("");
const isExpandAll = ref(true);
const refreshTable = ref(true);

const data = reactive({
  form: {},
  queryParams: {
    params:{},
    parentId: null,
    categoryTitle: null,
    categoryKeyword: null,
    categoryType: null,
    sort: null,
    isAdmin: null,
  },
  rules: {
    parentId: [{ required: true, message: "上级栏目不能为空", trigger: "blur" }],
    categoryTitle: [{ required: true, message: "栏目名称不能为空", trigger: "blur" }],
	  sort: [{ required: true, message: "排序不能为空", trigger: "blur" }],
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询栏目管理列表 */
function getList() {
  loading.value = true;
  listCmCategory(queryParams.value).then(response => {
    cmCategoryList.value = proxy.handleTree(response.data, "id", "parentId");
    loading.value = false;
  });
}

/** 查询栏目管理下拉树结构 */
function getTreeselect() {
  listCmCategory().then(response => {
    cmCategoryOptions.value = [];
    const data = { id: '0', categoryTitle: '顶级节点', children: [] };
    data.children = proxy.handleTree(response.data, "id", "parentId");
    cmCategoryOptions.value.push(data);
  });
}
	
// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    parentId: "0",
    categoryTitle: null,
    categoryImg: null,
    categoryKeyword: null,
    categoryType: 1,
    sort: 0,
    isAdmin: 0,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null,
    remark: null
  };
  proxy.resetForm("cmCategoryRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd(row) {
  reset();
  getTreeselect();
  if (row != null && row.id) {
    form.value.parentId = row.id;
  } else {
    form.value.parentId = 0;
  }
  open.value = true;
  title.value = "添加栏目管理";
}

/** 展开/折叠操作 */
function toggleExpandAll() {
  refreshTable.value = false;
  isExpandAll.value = !isExpandAll.value;
  nextTick(() => {
    refreshTable.value = true;
  });
}

/** 修改按钮操作 */
async function handleUpdate(row) {
  reset();
  await getTreeselect();
  if (row != null) {
    form.value.parentId = row.id;
  }
  getCmCategory(row.id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改栏目管理";
  });
}

/** 提交按钮 */
const cmCategoryRef = ref(null)
function submitForm() {
  cmCategoryRef.value.validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        proxy.modal.loading("提交中");
        updateCmCategory(form.value).then(response => {
          proxy.modal.msgSuccess("修改成功");
          open.value = false;
          proxy.modal.closeLoading();
          getList();
        }).catch(err=>{
            proxy.modal.closeLoading();
            Promise.reject(err);
        });;
      } else {
        proxy.modal.loading("提交中");
        addCmCategory(form.value).then(response => {
          proxy.modal.msgSuccess("新增成功");
          open.value = false;
          proxy.modal.closeLoading();
          getList();
        }).catch(err=>{
            proxy.modal.closeLoading();
            Promise.reject(err);
        });;
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  proxy.modal.confirm('是否确认删除栏目管理编号为"' + row.id + '"的数据项？').then(function() {
    return delCmCategory(row.id);
  }).then(() => {
    getList();
    proxy.modal.msgSuccess("删除成功");
  }).catch(() => {});
}


getList();
</script>
